﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.Objects.DataClasses;
using System.ComponentModel;

namespace Sequence
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private SalesManagerEntities _context = new SalesManagerEntities();
        private SalesManagerCodes _codesContext = new SalesManagerCodes();
        private CollectionViewSource _SequenceViewSource;
        private CollectionViewSource _carrierViewSource;
        private CollectionViewSource _SequenceStepsViewSource;
        private int _ownerID = 1;

        public Window1()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (App.Args.Count() == 0)
            {
                MessageBox.Show("No OwnerID specified");
                Close();
                return;
            }
            if (!int.TryParse(App.Args[0], out _ownerID))
            {
                MessageBox.Show("Invalid OwnerID specified");
                Close();
                return;
            }
            _context.ContextOptions.LazyLoadingEnabled = true;
            _SequenceViewSource = (CollectionViewSource)FindResource("Sequence");
            _SequenceStepsViewSource = (CollectionViewSource)FindResource("SequenceSteps");
            _SequenceViewSource.Source = from c in _context.tblSequence
                                              where c.OwnerID == _ownerID
                                              orderby c.Description
                                              select c;
            //_SequenceViewSource.View.CurrentChanged += new EventHandler(SequenceView_CurrentChanged);
            //SetSequenceStepsView();
            cmbSequence_SelectionChanged(null, null);

            var carrierList = (from c in _codesContext.codeCarrier
                                        select new {CarrierCode=(int?)c.CarrierCode, c.Description}).ToList();
            carrierList.Add( new { CarrierCode=(int?)null, Description=(string)null } );
            _carrierViewSource = (CollectionViewSource)FindResource("Carriers");
            _carrierViewSource.Source = carrierList;

            seqGraph.Initialize(_context, _ownerID);
        }

        private void SetSequenceStepsView()
        {
            if (_SequenceViewSource.View.CurrentItem != null)
            {
                _SequenceStepsViewSource.Source = ((tblSequence)_SequenceViewSource.View.CurrentItem).SequenceSteps.ToList();
                _SequenceStepsViewSource.SortDescriptions.Add(new SortDescription("Delay", ListSortDirection.Ascending));
            }
            else
                _SequenceStepsViewSource.Source = null;
        }

        private void SequenceView_CurrentChanged(object sender, EventArgs e)
        {
            tblSequence t = new tblSequence();
            SetSequenceStepsView();
        }

        private void btnNewSequence_Click(object sender, RoutedEventArgs e)
        {
            DialogProductList dlg = new DialogProductList(_ownerID);
            if ((bool)dlg.ShowDialog())
            {
                //tblSequence newSequence = new tblSequence();
                tblSequence newSequence = (tblSequence)((IEditableCollectionView)_SequenceViewSource.View).AddNew();
                ((IEditableCollectionView)_carrierViewSource.View).CommitNew();
                newSequence.Description = "New";
                newSequence.SequenceCode = "aaa";
                //newSequence.Product = (tblProduct)_context.GetObjectByKey(
                //    new System.Data.EntityKey("SalesManagerEntities.tblProduct", "ProductID", dlg.ProductID));
                _context.AddTotblSequence(newSequence);
                cmbSequence.SelectedItem = newSequence;
            }
        }

        private void cmbSequence_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_SequenceViewSource.View != null && _SequenceViewSource.View.CurrentItem != null)
            {
                tblSequence sequence = (tblSequence)_SequenceViewSource.View.CurrentItem;
                IQueryable<tblSequenceStep> sequenceSteps = from c in _context.tblSequenceStep
                                           where c.Sequence.SequenceID == sequence.SequenceID
                                           select c;
                _SequenceStepsViewSource.Source = sequenceSteps;

                tblSequenceStep[] steps = sequenceSteps.ToArray();

                if (steps.Length > 0)
                {
                    tblSequenceStep step = steps.FirstOrDefault(c => c.PrevSequenceStep == null);
                    step.StepOrder = 1;
                    RecurseSetStepOrder(step.NextSteps, 2);
                }
                if (_SequenceStepsViewSource.View != null)
                    _SequenceStepsViewSource.View.Refresh();
            }
        }

        private void RecurseSetStepOrder(EntityCollection<tblSequenceStep> steps, int level)
        {
            if (steps == null)
                return;
            foreach (tblSequenceStep step in steps)
            {
                step.StepOrder = level;
                RecurseSetStepOrder(step.NextSteps, level + 1);
            }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            _context.SaveChanges();
        }

        private void btnAddStep_Click(object sender, RoutedEventArgs e)
        {
            tblSequence Sequence = (tblSequence)_SequenceViewSource.View.CurrentItem;

            tblSequenceStep newStep = (tblSequenceStep)((IEditableCollectionView)_SequenceStepsViewSource.View).AddNew();
            ((IEditableCollectionView)_SequenceStepsViewSource.View).CommitNew();
            newStep.Delay = 0;
            newStep.RecurrenceCount = 0;
            newStep.RecurrenceTerm = 0;
            newStep.Sequence = Sequence;

            seqGraph.UpdateCanvas();
        }

        private void btnAddProduct_Click(object sender, RoutedEventArgs e)
        {
            tblSequenceStep SequenceStep = (tblSequenceStep)((Button)e.Source).CommandParameter;
            DialogProductList dlg = new DialogProductList(_ownerID);
            if ((bool)dlg.ShowDialog())
            {
                tblSequenceStepProduct newProduct = new tblSequenceStepProduct();
                newProduct.Product = (tblProduct)_context.GetObjectByKey(
                    new System.Data.EntityKey("SalesManagerEntities.tblProduct", "ProductID", dlg.ProductID));
                newProduct.SequenceStep = SequenceStep;
                newProduct.UnitPrice = 0;
                newProduct.Qty = 1;
            }
        }

        private void btnDeletePRoduct_Click(object sender, RoutedEventArgs e)
        {
            tblSequenceStepProduct SequenceStepProduct = (tblSequenceStepProduct)((Button)e.Source).CommandParameter;
            _context.DeleteObject(SequenceStepProduct);
        }

        private void btnDeleteTriggerProduct_Click(object sender, RoutedEventArgs e)
        {
            tblSequenceProduct SequenceProduct = (tblSequenceProduct)((Button)e.Source).CommandParameter;
            _context.DeleteObject(SequenceProduct);
        }

        private void btnAddSequenceProduct_Click(object sender, RoutedEventArgs e)
        {
            tblSequence Sequence = (tblSequence)((BindingListCollectionView)((Button)e.Source).CommandParameter).CurrentItem;
            DialogProductList dlg = new DialogProductList(_ownerID);
            if ((bool)dlg.ShowDialog())
            {
                tblSequenceProduct newProduct = new tblSequenceProduct();
                newProduct.Product = (tblProduct)_context.GetObjectByKey(
                    new System.Data.EntityKey("SalesManagerEntities.tblProduct", "ProductID", dlg.ProductID));
                newProduct.Sequence = Sequence;
            }
        }

        private void btnRemoveStep_Click(object sender, RoutedEventArgs e)
        {
            tblSequenceStep SequenceStep = (tblSequenceStep)((Button)e.Source).CommandParameter;
            tblSequenceStep nextStep = SequenceStep.NextSteps.First();

            if (nextStep != null)
            {
                nextStep.PrevSequenceStep = SequenceStep.PrevSequenceStep;
                nextStep.StepOrder--;
            }
            _context.DeleteObject(SequenceStep);
        }
    }
}
